#include "Widget.hpp"

#include "Core/DiamondGrid.hpp"
#include "Core/HexagonGrid.hpp"
#include "Core/RuleData.hpp"
#include "Core/SquareGrid.hpp"

#include "UI/DiamondRepresentation.hpp"
#include "UI/HexagonRepresentation.hpp"
#include "UI/SquareRepresentation.hpp"
#include "UI/Visualisation.hpp"

#include <QtCore/QTimer>

#include <QtGui/QPushButton>
#include <QtGui/QVBoxLayout>

#define SQUARE 1
#define HEXAGON 2
#define DIAMOND 3

#define TEST DIAMOND

Widget::Widget( QWidget* parent )
    : QWidget( parent )
    , Rules( new RuleData() )
    , Chronometer( new QTimer( this ) )
{
    setupUI();
}

Widget::~Widget()
{
    delete Rules;
}

void Widget::startAnimation()
{
    Chronometer -> start();
}

void Widget::setupUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout( this );
    setLayout( mainLayout );

#if TEST == SQUARE
    SquareGrid* model = new SquareGrid( 20u, 20u, this );
    SquareRepresentation* scene = new SquareRepresentation( model, this );
#elif TEST == HEXAGON
    HexagonGrid* model = new HexagonGrid( 20u, 20u, this );
    HexagonRepresentation* scene = new HexagonRepresentation( model, this );
#elif TEST == DIAMOND
    DiamondGrid* model = new DiamondGrid( 20u, 20u, this );
    DiamondRepresentation* scene = new DiamondRepresentation( model, this );
#endif

    Visualisation* view = new Visualisation( model, scene, this );

    Rules -> addBirthCondition( 3u );
    Rules -> addSurvivalCondition( 2u );
    Rules -> addSurvivalCondition( 3u );

    model -> setGameRules( Rules );

    connect( view, SIGNAL( clickedAt( QPointF ) ), scene, SLOT( retrieveCell( QPointF ) ) );
    connect( scene, SIGNAL( touchedCell( QPoint ) ), model, SLOT( flipCell( QPoint ) ) );

    Chronometer -> setInterval( 100 );

    connect( Chronometer, SIGNAL( timeout() ), model, SLOT( step() ) );

    QTimer::singleShot( 0, model, SLOT( initialise() ) );

    mainLayout -> addWidget( view );

    QPushButton* startButton = new QPushButton( tr( "Start" ), this );

    connect( startButton, SIGNAL( clicked() ), this, SLOT( startAnimation() ) );

    mainLayout -> addWidget( startButton, 0, Qt::AlignCenter );
}
